<template>
  <view class="reading-analytics">
    <!-- 头部统计卡片 -->
    <view class="stats-header">
      <view class="stat-card" @click="navigateToBooks">
        <text class="stat-value">{{totalBooks}}</text>
        <text class="stat-label">已读书籍</text>
        <view class="stat-trend" :class="{'up': booksTrend > 0, 'down': booksTrend < 0}">
          <uni-icons type="arrowup" size="14" color="#4ECB73" v-if="booksTrend > 0"></uni-icons>
          <uni-icons type="arrowdown" size="14" color="#FF6B6B" v-else-if="booksTrend < 0"></uni-icons>
          <text>{{Math.abs(booksTrend)}}%</text>
        </view>
      </view>
      <view class="stat-card highlight" @click="navigateToCalendar">
        <text class="stat-value">{{readingDays}}</text>
        <text class="stat-label">阅读天数</text>
        <view class="streak-badge">
          <uni-icons type="star-filled" size="14" color="#FFC107"></uni-icons>
          <text>连续{{currentStreak}}天</text>
        </view>
      </view>
      <view class="stat-card" @click="navigateToTime">
        <text class="stat-value">{{totalHours}}h</text>
        <text class="stat-label">阅读时长</text>
        <view class="stat-trend" :class="{'up': timeTrend > 0, 'down': timeTrend < 0}">
          <uni-icons type="arrowup" size="14" color="#4ECB73" v-if="timeTrend > 0"></uni-icons>
          <uni-icons type="arrowdown" size="14" color="#FF6B6B" v-else-if="timeTrend < 0"></uni-icons>
          <text>{{Math.abs(timeTrend)}}%</text>
        </view>
      </view>
    </view>

    <!-- 阅读趋势图表 -->
    <view class="chart-section">
      <view class="section-header">
        <text>阅读趋势</text>
        <picker mode="date" fields="month" @change="changeMonth">
          <view class="date-picker">
            <text>{{currentMonth}}</text>
            <uni-icons type="arrowdown" size="14" color="#666"></uni-icons>
          </view>
        </picker>
      </view>
      <view class="chart-container">
        <canvas canvas-id="readingTrendChart" id="readingTrendChart" type="2d" class="chart"></canvas>
      </view>
    </view>

    <!-- 书籍类型分布 -->
    <view class="distribution-section">
      <view class="section-header">
        <text>书籍类型分布</text>
        <view class="view-more" @click="navigateToGenres">
          <text>查看详情</text>
          <uni-icons type="forward" size="14" color="#2A5CAA"></uni-icons>
        </view>
      </view>
      <view class="chart-container">
        <canvas canvas-id="genreDistributionChart" id="genreDistributionChart" type="2d" class="chart"></canvas>
      </view>
      <view class="legend">
        <view v-for="(item, index) in genreData" :key="index" class="legend-item" @click="filterByGenre(item.name)">
          <view class="legend-color" :style="{backgroundColor: colors[index]}"></view>
          <text>{{item.name}} {{item.percentage}}%</text>
          <text class="book-count">{{item.value}}本</text>
        </view>
      </view>
    </view>

    <!-- 阅读时段分析 -->
    <view class="time-section">
      <view class="section-header">
        <text>阅读时段分布</text>
        <view class="time-filter">
          <text @click="changeTimeRange('week')" :class="{active: timeRange === 'week'}">本周</text>
          <text @click="changeTimeRange('month')" :class="{active: timeRange === 'month'}">本月</text>
          <text @click="changeTimeRange('year')" :class="{active: timeRange === 'year'}">全年</text>
        </view>
      </view>
      <view class="time-grid">
        <view v-for="(item, index) in timeData" :key="index" class="time-item" @click="showTimeDetail(item.time)">
          <text class="time-label">{{item.time}}</text>
          <view class="time-bar-container">
            <view class="time-bar" :style="{width: item.percentage + '%', backgroundColor: timeColors[index]}"></view>
          </view>
          <text class="time-percentage">{{item.percentage}}%</text>
        </view>
      </view>
    </view>

    <!-- 阅读效率评分 -->
    <view class="score-section">
      <view class="section-header">
        <text>阅读效率评分</text>
        <view class="refresh-btn" @click="refreshScore">
          <uni-icons type="refresh" size="16" color="#2A5CAA"></uni-icons>
          <text>更新评估</text>
        </view>
      </view>
      <view class="score-container">
        <view class="gauge-chart">
          <view class="gauge-background"></view>
          <view class="gauge-mask" :style="{transform: `rotate(${efficiencyScore * 1.8}deg)`}"></view>
          <text class="gauge-score">{{efficiencyScore}}</text>
          <text class="gauge-label">效率评分</text>
        </view>
        <view class="score-details">
          <view class="detail-item">
            <text class="detail-label">专注度</text>
            <view class="progress-bar">
              <view class="progress-fill" :style="{width: concentrationScore*10 + '%', backgroundColor: getProgressColor(concentrationScore)}"></view>
            </view>
            <text class="detail-value">{{concentrationScore}}/10</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">阅读速度</text>
            <view class="progress-bar">
              <view class="progress-fill" :style="{width: Math.min(speedScore/5, 100) + '%', backgroundColor: getSpeedColor(speedScore)}"></view>
            </view>
            <text class="detail-value">{{speedScore}}字/分钟</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">理解度</text>
            <view class="progress-bar">
              <view class="progress-fill" :style="{width: comprehensionScore*10 + '%', backgroundColor: getProgressColor(comprehensionScore)}"></view>
            </view>
            <text class="detail-value">{{comprehensionScore}}/10</text>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import uCharts from '@qiun/ucharts'

export default {
  data() {
    return {
      totalBooks: 0,
      readingDays: 0,
      totalHours: 0,
      currentStreak: 0,
      booksTrend: 0,
      timeTrend: 0,
      currentMonth: '',
      efficiencyScore: 0,
      concentrationScore: 0,
      comprehensionScore: 0,
      speedScore: 0,
      timeRange: 'week',
      colors: ['#2A5CAA', '#4ECB73', '#FFC107', '#FF6B6B', '#9C27B0'],
      timeColors: ['#2A5CAA', '#4ECB73', '#FFC107', '#FF6B6B'],
      genreData: [],
      timeData: [],
      trendChart: null,
      pieChart: null
    }
  },
  onLoad() {
    this.loadData()
  },
  onReady() {
    // 延迟初始化确保canvas渲染完成
    setTimeout(() => {
      this.initCharts()
    }, 300)
  },
  onUnload() {
    this.disposeCharts()
  },
  methods: {
    async loadData() {
      uni.showLoading({ title: '加载中...' })
      try {
        const res = await uni.$http.get('/user-reading-data')
        // 处理后端返回的数据结构，获取真正的数据部分
        const data = res.data.data 
        this.totalBooks = data.totalBooks
        this.readingDays = data.readingDays
        this.totalHours = data.totalHours
        this.currentStreak = data.currentStreak
        this.booksTrend = data.booksTrend
        this.timeTrend = data.timeTrend
        this.currentMonth = data.currentMonth
        this.efficiencyScore = data.efficiencyScore
        this.concentrationScore = data.concentrationScore
        this.comprehensionScore = data.comprehensionScore
        this.speedScore = data.speedScore
        this.genreData = data.genreData
        this.timeData = data.timeData

        // 更新趋势图表数据
        if (this.trendChart) {
          const chartData = {
            categories: this.timeData.map(item => item.time),
            series: [{
              name: '阅读时长',
              data: this.timeData.map(item => item.value),
              color: '#2A5CAA'
            }]
          }
          this.trendChart.updateData({
            categories: chartData.categories,
            series: chartData.series
          })
        }

        // 更新饼图数据
        if (this.pieChart) {
          const chartData = {
            series: this.genreData.map(item => {
              return {data: item.value, name: item.name}
            }),
            colors: this.colors
          }
          this.pieChart.updateData({
            series: chartData.series,
            colors: chartData.colors
          })
        }
      } catch (e) {
        console.error(e)
        uni.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    initCharts() {
      this.initTrendChart()
      this.initPieChart()
    },
    initTrendChart() {
      const query = uni.createSelectorQuery().in(this)
      query.select('#readingTrendChart').fields({ node: true, size: true }).exec(res => {
        if (!res[0]) return

        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const pixelRatio = uni.getSystemInfoSync().pixelRatio

        canvas.width = res[0].width * pixelRatio
        canvas.height = res[0].height * pixelRatio

        const chartData = {
          categories: this.timeData.map(item => item.time),
          series: [{
            name: '阅读时长',
            data: this.timeData.map(item => item.value),
            color: '#2A5CAA'
          }]
        }

        this.trendChart = new uCharts({
          $this: this,
          canvasId: 'readingTrendChart',
          type: 'line',
          context: ctx,
          width: canvas.width,
          height: canvas.height,
          categories: chartData.categories,
          series: chartData.series,
          animation: true,
          background: '#FFFFFF',
          padding: [15, 15, 0, 15],
          dataLabel: true,
          dataPointShape: true,
          extra: {
            line: {
              type: 'curve',
              width: 2,
              activeType: 'point'
            },
            tooltip: {
              showBox: true
            }
          }
        })
      })
    },
    initPieChart() {
      const query = uni.createSelectorQuery().in(this)
      query.select('#genreDistributionChart').fields({ node: true, size: true }).exec(res => {
        if (!res[0]) return

        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const pixelRatio = uni.getSystemInfoSync().pixelRatio

        canvas.width = res[0].width * pixelRatio
        canvas.height = res[0].height * pixelRatio

        const chartData = {
          series: this.genreData.map(item => {
            return {data: item.value, name: item.name}
          }),
          colors: this.colors
        }

        this.pieChart = new uCharts({
          $this: this,
          canvasId: 'genreDistributionChart',
          type: 'pie',
          context: ctx,
          width: canvas.width,
          height: canvas.height,
          series: chartData.series,
          colors: chartData.colors,
          animation: true,
          background: '#FFFFFF',
          padding: [15, 15, 15, 15],
          extra: {
            pie: {
              labelTextSize: 14,
              legendTextSize: 14,
              offsetAngle: 0,
              activeOpacity: 0.8,
              inactiveOpacity: 0.5,
              strokeWidth: 0,
              strokeColor: '#FFFFFF'
            },
            tooltip: {
              showBox: true
            }
          }
        })
      })
    },
    disposeCharts() {
      if (this.trendChart) {
        this.trendChart.dispose()
        this.trendChart = null
      }
      if (this.pieChart) {
        this.pieChart.dispose()
        this.pieChart = null
      }
    },
    changeMonth(e) {
      const date = new Date(e.detail.value)
      this.currentMonth = `${date.getFullYear()}年${date.getMonth() + 1}月`
      // 这里应该重新加载数据
      this.loadMonthData(date)
    },
    changeTimeRange(range) {
      this.timeRange = range
      // 重新加载时段数据
      this.loadTimeData(range)
    },
    getProgressColor(score) {
      if (score >= 8) return '#4ECB73'
      if (score >= 5) return '#FFC107'
      return '#FF6B6B'
    },
    getSpeedColor(speed) {
      if (speed >= 400) return '#4ECB73'
      if (speed >= 250) return '#FFC107'
      return '#FF6B6B'
    },
    refreshScore() {
      uni.showLoading({ title: '评估中...' })
      setTimeout(() => {
        // 模拟重新评估
        this.efficiencyScore = Math.min(100, this.efficiencyScore + Math.floor(Math.random() * 5))
        this.concentrationScore = Math.min(10, this.concentrationScore + 0.5)
        this.comprehensionScore = Math.min(10, this.comprehensionScore + 0.3)
        this.speedScore = Math.min(500, this.speedScore + 20)
        uni.hideLoading()
        uni.showToast({ title: '评估完成', icon: 'success' })
      }, 1500)
    },
    exportData() {
      uni.showActionSheet({
        itemList: ['导出为PDF', '导出为图片', '导出为Excel'],
        success: (res) => {
          uni.showToast({ title: `正在导出${['PDF','图片','Excel'][res.tapIndex]}`, icon: 'none' })
        }
      })
    },
    shareData() {
      uni.share({
        provider: 'weixin',
        type: 0,
        title: '我的阅读数据报告',
        summary: `我已阅读${this.totalBooks}本书，累计${this.totalHours}小时，效率评分为${this.efficiencyScore}分！`,
        success: () => {
          uni.showToast({ title: '分享成功', icon: 'success' })
        }
      })
    },
    navigateToBooks() {
      uni.navigateTo({ url: '/pages/book-list/book-list' })
    },
    navigateToCalendar() {
      uni.navigateTo({ url: '/pages/reading-calendar/reading-calendar' })
    },
    navigateToTime() {
      uni.navigateTo({ url: '/pages/reading-time/reading-time' })
    },
    navigateToGenres() {
      uni.navigateTo({ url: '/pages/book-genres/book-genres' })
    },
    filterByGenre(genre) {
      uni.showToast({ title: `筛选: ${genre}`, icon: 'none' })
    },
    showTimeDetail(time) {
      uni.showToast({ title: `时段详情: ${time}`, icon: 'none' })
    },
    loadMonthData(date) {
      // 加载指定月份的数据
      console.log('加载月份数据:', date)
    },
    loadTimeData(range) {
      // 加载时段数据
      console.log('加载时段数据:', range)
    }
  }
}
</script>

<style lang="scss">
.reading-analytics {
  padding: 15px;
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 80px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;

  .stat-card {
    flex: 1;
    background-color: #fff;
    border-radius: 12px;
    padding: 15px;
    margin: 0 5px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    position: relative;
    overflow: hidden;

    &.highlight {
      background-color: #2A5CAA;
      color: #fff;

      .stat-value, .stat-label {
        color: #fff;
      }

      .streak-badge {
        background-color: rgba(255,255,255,0.2);
        color: #fff;
      }
    }

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 12px;
      color: #666;
      display: block;
      margin-bottom: 8px;
    }

    .stat-trend {
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;

      &.up {
        color: #4ECB73;
      }

      &.down {
        color: #FF6B6B;
      }
    }

    .streak-badge {
      display: inline-flex;
      align-items: center;
      padding: 2px 6px;
      border-radius: 10px;
      background-color: #f0f0f0;
      font-size: 12px;
      color: #666;

      .uni-icons {
        margin-right: 3px;
      }
    }
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0 15px;
  font-size: 16px;
  font-weight: bold;
  color: #333;

  .date-picker {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
    font-weight: normal;

    .uni-icons {
      margin-left: 5px;
    }
  }

  .view-more {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #2A5CAA;

    .uni-icons {
      margin-left: 3px;
    }
  }

  .refresh-btn {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #2A5CAA;

    .uni-icons {
      margin-right: 3px;
    }
  }

  .time-filter {
    display: flex;
    font-size: 12px;

    text {
      margin-left: 10px;
      padding: 2px 6px;
      border-radius: 3px;
      color: #666;

      &.active {
        background-color: #2A5CAA;
        color: #fff;
      }
    }
  }
}

.chart-section, .distribution-section, .time-section, .score-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.chart-container {
  width: 100%;
  height: 350rpx;

  .chart {
    width: 100%;
    height: 100%;
  }
}

.legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 15px;

  .legend-item {
    display: flex;
    align-items: center;
    width: 48%;
    margin-bottom: 10px;
    font-size: 12px;
    padding: 5px;
    border-radius: 4px;

    &:active {
      background-color: #f0f0f0;
    }

    .legend-color {
      width: 12px;
      height: 12px;
      border-radius: 2px;
      margin-right: 8px;
    }

    .book-count {
      margin-left: auto;
      color: #999;
    }
  }
}

.time-grid {
  .time-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    padding: 8px 0;

    &:active {
      background-color: #f5f5f5;
      border-radius: 6px;
    }

    .time-label {
      width: 90px;
      font-size: 13px;
      color: #666;
    }

    .time-bar-container {
      flex: 1;
      height: 8px;
      background-color: #eee;
      border-radius: 4px;
      margin: 0 10px;
      overflow: hidden;

      .time-bar {
        height: 100%;
        border-radius: 4px;
        transition: width 0.3s ease;
      }
    }

    .time-percentage {
      width: 40px;
      text-align: right;
      font-size: 13px;
      color: #666;
    }
  }
}

.score-container {
  display: flex;

  .gauge-chart {
    position: relative;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 15px;

    .gauge-background {
      position: absolute;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: conic-gradient(
        #4ECB73 0%, 
        #A5D6A7 25%, 
        #FFC107 50%, 
        #FFAB91 75%, 
        #FF6B6B 100%
      );
      z-index: 0;
    }

    .gauge-mask {
      position: absolute;
      width: 120px;
      height: 120px;
      background-color: #fff;
      border-radius: 50%;
      top: 15px;
      left: 15px;
      transform-origin: center;
      z-index: 1;
      transition: transform 0.6s ease;
    }

    .gauge-score {
      font-size: 28px;
      font-weight: bold;
      color: #333;
      z-index: 2;
    }

    .gauge-label {
      font-size: 12px;
      color: #666;
      z-index: 2;
      margin-top: 5px;
    }
  }

  .score-details {
    flex: 1;

    .detail-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .detail-label {
        width: 60px;
        font-size: 13px;
        color: #666;
      }

      .progress-bar {
        flex: 1;
        height: 6px;
        background-color: #eee;
        border-radius: 3px;
        margin: 0 10px;
        overflow: hidden;

        .progress-fill {
          height: 100%;
          border-radius: 3px;
          transition: width 0.3s ease;
        }
      }

      .detail-value {
        width: 70px;
        font-size: 13px;
        color: #333;
        text-align: right;
      }
    }
  }
}

</style>    